#include "RankCalculator.h"

enum SpacingType { EXTRACOLUMNSFROMLEFT = 2, TOTALEXTRAROW = 1, RECORDSTARTING = 2, RECORDSTARTING_Y = 1, TOTALEXTRACOLUMNS = 7, EXTRACOLUMNS_V = 2, EXTRACOLUMNS_F = 3, EXTRACOLUMNS_A = 4, EXTRACOLUMNS_I = 5, EXTRACOLUMNS_R = 6 }; 

RankCalculator::RankCalculator( QWidget* parent ) 
	: QMainWindow( parent ),
	questionGroupBox( 0 ),
	groupMatrixGroupBox( 0 ),
	calculateAndOptionsGroupBox( 0 ),
	questionLabel( 0 ),
	questionLineEdit( 0 ),
	questionButton( 0 ),
	gridVerticalLayout( 0 ),
	questionHorizontalLayout( 0 ),
	groupMatrixGridLayout( 0 ),
    calculateAndOptionsHorizontalLayout( 0 ),
    radioVector( 0 ),
	numberOfFencers( 10 ){
		ui.setupUi( this );

		//QMapIterator<QString, QLineEdit*> i(map_1);
		//while (i.hasNext()){
		//	i.next();
		//	qDebug() << i.key() << ": " << i.value()->text();
		//}
		createQuestionGroupBox();
		createGroupMatrixGroupBox();
		createCalculateAndOptionsGroupBox();
		ui.gridLayout->addWidget( questionGroupBox, 0, 0 );
		ui.gridLayout->setSpacing( 0 );
}

QString RankCalculator::createQuestionGroupBox(){
	questionGroupBox = new QGroupBox( tr( "Question" ) );
	questionGroupBox->setMaximumHeight( 100 );
	questionLabel = new QLabel( "Number of fencers: " );
	questionLineEdit = new QLineEdit;
	QRegExp rx("^[2-9]$|^10$|^1[1-9]$|^20$");
	//QRegExp rx("^([2-9]\d|[1-9]\d{2,})$");
	QValidator* validator = new QRegExpValidator(rx, this);
    QString lineStyle = "QLineEdit { border-radius: 3px }";
	questionLineEdit->setValidator( validator );
    questionLineEdit->setStyleSheet( lineStyle );
	questionButton = new QPushButton( "Generate" );	
	questionHorizontalLayout = new QHBoxLayout;
	questionHorizontalLayout->addWidget( questionLabel );
	questionHorizontalLayout->addWidget( questionLineEdit );
	questionHorizontalLayout->addWidget( questionButton );
	questionHorizontalLayout->addStretch( 400 );
	questionGroupBox->setLayout( questionHorizontalLayout );
	connect( questionLineEdit, SIGNAL( textEdited( const QString & ) ), this, SLOT( numberOfFencersChanged( const QString & ) ) );
	connect(questionButton, SIGNAL( clicked( bool ) ), this, SLOT( nextButtonPressed() ) );
	return "Succeeded Creating Question GroupBox";
}

//requires group number as global value
QString RankCalculator::createGroupMatrixGroupBox(){
	groupMatrixGroupBox = new QGroupBox( tr( "Matrix" ) );
	groupMatrixGridLayout = new QGridLayout( groupMatrixGroupBox );
	groupMatrixGridLayout->setSpacing( 0.5 );
	groupMatrixGroupBox->setLayout( groupMatrixGridLayout );

	QStringList firstRowLabel;
	firstRowLabel << "V";
	firstRowLabel << "TS";
	firstRowLabel << "TR";
	firstRowLabel << "Ind";
	firstRowLabel << "Pl";
	for ( int y = 0; y < numberOfFencers + TOTALEXTRAROW; ++y ){
		//y row
		//+1 horizontal row Pointers For, Point Against, Indicator, Final Rank Labels
		//+2 horizontal row Fencers Name Labels 
		for ( int x = 0; x < numberOfFencers + TOTALEXTRACOLUMNS; ++x ){
			//x columns
			//+1 number of fencers column Label
			//+2 vertical column Fencers Name LineEdits
			//+3 V victory number
			//+4 F Point For Column Label TS
			//+5 A Point Against Column Label TR
			//+6 I Indicator Column Label Ind
			//+7 R Rank Column Label Pl
			if ( y == 0 ){ //if column is in row 0 it means the top label row
				if ( x < EXTRACOLUMNSFROMLEFT ){
					//QString labelIndex = QString::number( y ) + "-" + QString::number( x );
				}else if ( x <= ( numberOfFencers + 1 ) ){ // row 0 column not yet to label column adding 1 for fencer number column
					QString labelIndex = QString::number( y ) + "-" + QString::number( x );
					//set empty label
					QLabel* newLabel = new QLabel( QString::number( x - 1 ), groupMatrixGroupBox );
					//add to map to keep track
					newLabel->setMinimumWidth( 40 );
					newLabel->setMaximumWidth( 40 );
					newLabel->setMinimumHeight( 30 );
					newLabel->setAlignment( Qt::AlignCenter );
					labelMap.insert( labelIndex, newLabel );
					groupMatrixGridLayout->addWidget( newLabel, y, x );
				}else{ // reaching label column every column adding 1 for fencer number column
					QString labelString = "";
					if ( x == numberOfFencers + EXTRACOLUMNS_V )
						labelString = firstRowLabel.at( 0 );
					else if ( x == numberOfFencers + EXTRACOLUMNS_F )
						labelString = firstRowLabel.at( 1 );
					else if ( x == numberOfFencers + EXTRACOLUMNS_A )
						labelString = firstRowLabel.at( 2 );
					else if ( x == numberOfFencers + EXTRACOLUMNS_I )
						labelString = firstRowLabel.at( 3 );
					else if ( x == numberOfFencers + EXTRACOLUMNS_R )
						labelString = firstRowLabel.at( 4 );

					QString labelIndexForMap = QString::number( y ) + "-" + QString::number( x );
					QLabel* newLabel = new QLabel( labelString, groupMatrixGroupBox );
					newLabel->setMinimumWidth( 40 );
					newLabel->setMaximumWidth( 40 );
					//newLabel->setMaximumHeight( 50 );
					newLabel->setMinimumHeight( 30 );
					newLabel->setAlignment( Qt::AlignCenter );
					labelMap.insert( labelIndexForMap, newLabel );
					groupMatrixGridLayout->addWidget( newLabel, y, x );
				}
			}else{
				if ( x == 0 ){
					//fencer name column
					QString lineIndex = QString::number( y ) + "-" + QString::number( x );
					QLineEdit* newLine = new QLineEdit( "", groupMatrixGroupBox );
					//newLine->setDisabled( 1 );
					newLine->setMinimumHeight( 30 );
					newLine->setMinimumWidth( 100 );
                    newLine->setAlignment( Qt::AlignCenter );
                    //QString lineStyle = "QLineEdit { border-radius: 5px; background-color: black; }";
                    //newLine->setStyleSheet( lineStyle );
					lineMap.insert( lineIndex, newLine );
					groupMatrixGridLayout->addWidget( newLine, y, x );
				}else if ( x == 1 ){
					QString labelIndex = QString::number( y ) + "-" + QString::number( x );
					QLabel* newLabel = new QLabel( QString::number( y ), groupMatrixGroupBox );
					newLabel->setMinimumWidth( 40 );
					newLabel->setMaximumWidth( 40 );
					newLabel->setMinimumHeight( 30 );
					newLabel->setAlignment( Qt::AlignCenter );
					labelMap.insert( labelIndex, newLabel );
					groupMatrixGridLayout->addWidget( newLabel, y, x );
				}else if ( y == x - 1){
					//against self column, use label, and put place holder text
					QString labelIndex = QString::number( y ) + "-" + QString::number( x );
					QLabel* newLabel = new QLabel( "", groupMatrixGroupBox );
					newLabel->setMinimumWidth( 40 );
					newLabel->setMaximumWidth( 40 );
					newLabel->setMinimumHeight( 30 );
					newLabel->setAlignment( Qt::AlignCenter );
					newLabel->setFrameStyle( QFrame::Panel | QFrame::Plain );
					newLabel->setLineWidth( 2 );
					QString labelStyle = "QLabel { border-radius: 3px; background-color: black; }";
					newLabel->setStyleSheet( labelStyle );
					labelMap.insert( labelIndex, newLabel );
					groupMatrixGridLayout->addWidget( newLabel, y, x );
				}else if ( x <= numberOfFencers + 1){
					//record lineedit, use lineedit, and set empty text
					QString lineIndex = QString::number( y ) + "-" + QString::number( x );
					QLineEdit* newLine = new QLineEdit( "", groupMatrixGroupBox );
					newLine->setMinimumHeight( 30 );
					newLine->setMinimumWidth( 40 );
					newLine->setMaximumWidth( 40 );
                    newLine->setAlignment( Qt::AlignCenter );
                    QString lineStyle = "QLineEdit { border-radius: 5px }";
                    newLine->setStyleSheet( lineStyle );
					lineMap.insert( lineIndex, newLine );
					groupMatrixGridLayout->addWidget( newLine, y, x );
				}else{
					//FAIR column, use label, and empty text
					QString labelIndex = QString::number( y ) + "-" + QString::number( x );
					//set empty label
					QLabel* newLabel = new QLabel( "", groupMatrixGroupBox );
					newLabel->setMinimumHeight( 30 );
					newLabel->setMinimumWidth( 40 );
					newLabel->setMaximumWidth( 40 );
					newLabel->setAlignment( Qt::AlignCenter );
					//add to map to keep track
					labelMap.insert( labelIndex, newLabel );
					groupMatrixGridLayout->addWidget( newLabel, y, x );
				}
			}
		}

	}
	ui.gridLayout->addWidget( groupMatrixGroupBox, 1, 0 );
	return "Succeeded Creating Group Matrix GroupBox";
}

QString RankCalculator::createCalculateAndOptionsGroupBox(){
    //if ( radioVector != 0 )
    //    delete radioVector;
	QVector<QRadioButton* > *tempRadioVector = radioVector;
    calculateAndOptionsGroupBox = new QGroupBox( tr( "Options And Action" ) );
    calculateAndOptionsGroupBox->setMaximumHeight( 100 );
    QPushButton* calculateButton = new QPushButton( "Calculate", calculateAndOptionsGroupBox );
    QLabel* victoryOptionLabel = new QLabel( "Victory Type:", calculateAndOptionsGroupBox );
	horizontalSpacer = new QSpacerItem( 40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum );
    QRadioButton* fiveVictoryRadioButton = new QRadioButton( "5", calculateAndOptionsGroupBox );
    QRadioButton* fifteenVictoryRadioButton = new QRadioButton( "15", calculateAndOptionsGroupBox );
    radioVector = new QVector<QRadioButton*>;
    radioVector->append(fiveVictoryRadioButton);
    radioVector->append(fifteenVictoryRadioButton);
    calculateAndOptionsHorizontalLayout = new QHBoxLayout;
    calculateAndOptionsGroupBox->setLayout( calculateAndOptionsHorizontalLayout );
    calculateAndOptionsHorizontalLayout->addWidget( victoryOptionLabel );
    calculateAndOptionsHorizontalLayout->addWidget( fiveVictoryRadioButton );
    calculateAndOptionsHorizontalLayout->addWidget( fifteenVictoryRadioButton );
	calculateAndOptionsHorizontalLayout->addItem( horizontalSpacer );
    calculateAndOptionsHorizontalLayout->addWidget( calculateButton );
	fifteenVictoryRadioButton->setChecked( 1 );
    connect( calculateButton, SIGNAL( clicked( bool ) ), this, SLOT( calculateButtonPressed() ) );
    ui.gridLayout->addWidget( calculateAndOptionsGroupBox, 2, 0 );
	delete tempRadioVector;
    return "Succeeded Creating Calculate And Options GroupBox";
}
QString RankCalculator::numberOfFencersChanged( const QString & fenNum ){
	numberOfFencers = fenNum.toInt();
	qDebug() << numberOfFencers;
	return "Succeeded Updating Number of Fencers";
}

QString RankCalculator::nextButtonPressed(){
	QGroupBox* tempGroupBox_1 = groupMatrixGroupBox;
	//if ( groupMatrixGroupBox != 0 )
	//	delete groupMatrixGroupBox;
	//if ( calculateAndOptionsGroupBox != 0 )
	//	delete calculateAndOptionsGroupBox;
	//createGroupMatrixGroupBox();
	//createCalculateAndOptionsGroupBox();
	QGroupBox* tempGroupBox_2 = calculateAndOptionsGroupBox;
	createGroupMatrixGroupBox();
	createCalculateAndOptionsGroupBox();
	delete tempGroupBox_1;
	delete tempGroupBox_2;
	return "Succeeded Processing Next Button";
}

QString RankCalculator::calculateButtonPressed(){
	recordListF.clear();
	recordListA.clear();
    recordListV.clear();
	seedMap.clear();
	seedVector.clear();

	//get list of score F
	for ( int y = RECORDSTARTING_Y; y < numberOfFencers + TOTALEXTRAROW; ++y ){
		int perFencerTotal = 0;
        int perFencerVictory = 0;
		for ( int x = RECORDSTARTING; x < numberOfFencers + EXTRACOLUMNS_V; ++x ){
			if ( ( x - 1 ) != y ){
				QString lineIndex = QString::number( y ) + "-" + QString::number( x );
                if ( QString::compare( lineMap[lineIndex]->text().toUpper(), "V", Qt::CaseSensitive ) == 0 ){
                    perFencerTotal = perFencerTotal + returnRadioTextAsInt();
                    ++perFencerVictory;
                }else
                    perFencerTotal = perFencerTotal + lineMap[lineIndex]->text().toInt();
			}
				
		}
		recordListF << perFencerTotal;
        recordListV << perFencerVictory;
	}

	//get list of score A
	for ( int x = RECORDSTARTING; x < numberOfFencers + EXTRACOLUMNS_V; ++x ){
		int perFencerTotal = 0;
		for ( int y = RECORDSTARTING_Y; y < numberOfFencers + TOTALEXTRAROW; ++y ){
			if ( y != ( x - 1 ) ){
				QString lineIndex = QString::number( y ) + "-" + QString::number( x );
                if ( QString::compare( lineMap[lineIndex]->text().toUpper(), "V", Qt::CaseSensitive ) == 0 )
                    perFencerTotal = perFencerTotal + returnRadioTextAsInt();
                else
                    perFencerTotal = perFencerTotal + lineMap[lineIndex]->text().toInt();
			}
		}
		recordListA << perFencerTotal;
	}

    //assign score to appropriate label recordListF.length() == number of fencers;
	const int fColumnNumber = recordListF.length() + EXTRACOLUMNS_F;
	const int aColumnNumber = recordListA.length() + EXTRACOLUMNS_A;
	const int iColumnNumber = recordListF.length() + EXTRACOLUMNS_I;
    const int vColumnNumber = recordListF.length() + EXTRACOLUMNS_V;
	//const int rColumnNumber = recordListR.length() + EXTRACOLUMNS_R;
	for ( int z = 0; z < recordListF.length(); ++z ){
        qDebug() << "V: " << recordListV.at( z );
		qDebug() << "F: " << recordListF.at( z );
		qDebug() << "A: " << recordListA.at( z );
		qDebug() << "I: " << recordListF.at( z ) - recordListA.at( z );
		//qDebug() << "R: " << recordListR.at(z);
        QString labelVIndex = QString::number( RECORDSTARTING_Y + z ) + "-" + QString::number( vColumnNumber );
		QString labelFIndex = QString::number( RECORDSTARTING_Y + z ) + "-" + QString::number( fColumnNumber );
		QString labelAIndex = QString::number( RECORDSTARTING_Y + z ) + "-" + QString::number( aColumnNumber );
		QString labelIIndex = QString::number( RECORDSTARTING_Y + z ) + "-" + QString::number( iColumnNumber );
		//QString labelFIndex = QString::number(RECORDSTARTING + z) + "-" + QString::number(fColumnNumber);
        labelMap[labelVIndex]->setText( QString::number( recordListV.at( z ) ) );
		labelMap[labelFIndex]->setText( QString::number( recordListF.at( z ) ) );
		labelMap[labelAIndex]->setText( QString::number( recordListA.at( z ) ) );
		labelMap[labelIIndex]->setText( QString::number( recordListF.at( z ) - recordListA.at( z ) ) );
		seedMap.insertMulti( labelMap[labelIIndex]->text().toInt(), labelIIndex );
	}
	//seedMap key = score; value = label#
	qDebug() << seedMap.size();
	QMapIterator<int, QString> i( seedMap );
	while ( i.hasNext() ){
		i.next();
		qDebug() << i.key() << ": " << i.value() << endl;
	}

	QMap<int, QString>::iterator j = seedMap.end();
	while ( j != seedMap.begin() ){
		--j;
		qDebug() << "placement score: " << j.key() << "; label: " << j.value();
		QPair<int, QString>* newPair = new QPair<int, QString>( j.key(), j.value());
		seedVector << newPair;
	}

	//seedVector newPair first = score; second = label#
	for ( int k = 0; k < seedVector.size(); ++k ){
		qDebug() << "placement: " << k + 1 << "; label: " << seedVector.at( k )->second << "; score: " << seedVector.at( k )->first;
	}

	for ( int k = 0; k < seedVector.size(); ++k ){
		delete seedVector.at( k );
	}

	return "Succeeded Processing Calculate Button";
}

